




from datetime import datetime
import json
import os
from PySide6 import QtCore
from PySide6.QtCore import Slot, QTimer, Qt, QDate, QTime, Signal, SLOT, QByteArray, QDateTime,QCoreApplication
from PySide6.QtGui import QColor, QImage, QTextCursor
from PySide6.QtWidgets import QWidget, QMessageBox, QLineEdit, QCheckBox, QTableWidgetItem, QComboBox, QInputDialog, \
    QFileDialog, QDateTimeEdit,QDialog

from gui.schemas.enumeration import AnnotationStatus, CommentStatus, UserRole
from gui.ui.UI_main_window import Ui_MainWindow
from gui.ui.UI_add_job_window import Ui_Form_add_jobspace

import requests
import traceback

from gui.utils.annotation_manager import DataManager


class Add_Job_Panel(Ui_Form_add_jobspace, QDialog):
    def __init__(self, parent=None):
        super(Add_Job_Panel, self).__init__()
        """
        1. 检查登录状态
        2. pushButton_synchronous 未登录不可点击
        2. pushButton_synchronous 定时检查更新登录状态
        """
        self.setupUi(self)
        self.parentWidget: QWidget = parent
        self.comboBox_file_type.currentTextChanged.connect(self.change_select_job_name)
        self.comboBox_select_model.currentTextChanged.connect(self.change_select_job_name)
        self.pushButton_seltct_work_dir.clicked.connect(self.clicked_seltct_work_dir)
        self.pushButton_add.clicked.connect(self.clicked_add_job)
        
    def showEvent(self, event):
        # 对话框显示前执行
        # 可以在这里加载数据或执行初始化
        models = self.parentWidget.data_manager.get_all_models()
        self.comboBox_select_model.clear()
        for model_name,model in models.items():
            self.comboBox_select_model.addItem(model_name,model)
        super().showEvent(event)  # 调用基类实现
        
    
    def change_select_job_name(self) -> None:
        self.lineEdit_job_name.setText(f"""{self.comboBox_file_type.currentText()}_{self.comboBox_select_model.currentText()}__{datetime.now().isoformat().replace(":", "-")}""")


    def clicked_seltct_work_dir(self) -> None:
        """
        设置工作文件的网络地址目录
        """
        options = QFileDialog.Options()
        options |= QFileDialog.ShowDirsOnly          # 只显示目录
        options |= QFileDialog.DontResolveSymlinks   # 不解析符号链接
        options |= QFileDialog.DontUseNativeDialog   # 使用Qt内置对话框
        options |= QFileDialog.ReadOnly              # 只读模式加速加载
        file_path = QFileDialog.getExistingDirectory(self, "选择工作目录", "",options=options)
        if file_path:
            self.lineEdit_file_network_prefix.setText(file_path)
        
    def clicked_add_job(self) -> None:
        """
        添加工作有几种情况
        管理权限的用户：
            添加后显示所有工作
            1. 将文件网络地址、
        标注权限的用户：
            正常情况下普通用户不能添加作业，但如果网络不通的情况下，就需要手动添加，
            但作业名称 必须要 redis 已有的作业名称，其文件选择类型、模型必须要和一致
            1. 设置指定名称，改名称必须要redis具有的作业名称，由管理员提供的
            2. 选择本地文件或目录、选择类型、模型，文件可为空
        
        """
        data_manager:DataManager = self.parentWidget.data_manager
        username = self.parentWidget.userinfo.get("username")
        role = self.parentWidget.userinfo.get("role", [])
        if UserRole.ADMIN in role: # 具有管理员权限
            """
            管理员添加作业到redis ，不需要添加到本地
            因为管理员只是添加管理作业，而不是标注
            如果需要标注，就同步下载文件到本地
            """
            try:
                tab_name = self.lineEdit_job_name.text()
                # 检查Tab是否已存在
                jobs = data_manager.get_jobs()
                if tab_name in jobs:
                    QMessageBox.warning(self, "错误", f"作业'{tab_name}' 已存在")
                    return
                file_path = self.lineEdit_file_network_prefix.text()
                file_type = self.comboBox_file_type.currentText()
                model_config = self.comboBox_select_model.currentData(Qt.ItemDataRole.UserRole)
                labels = model_config.get("labels", [])
                now = datetime.now()
                tab_data = {
                    "name": tab_name,
                    "base_url": file_path,
                    "model_name": self.comboBox_select_model.currentText(),
                    "labels": labels,
                    "createtime": now.isoformat(),
                    "file_type": file_type,
                    "updatetime": now.isoformat(),
                    "user_metadata": {
                        "config": {},
                        "job": {
                            "current_filename": ""
                        }
                    }
                }
                # 对于快捷键设置等模型用户配置，这里可以添加到redis： model:username:model_name ，未实现
                # 添加到redis
                select_files = self.plainTextEdit_select_files.toPlainText()
                select_files.split("\n")
                select_files = [filename.strip() for filename in select_files if filename.strip()]
                if not file_path.startswith("http") and os.path.exists(file_path): # 可以是https
                    filenames = os.listdir(file_path)
                    select_files = list(set(filenames+select_files))
                select_files.sort()
                data_manager.create_job(tab_data,select_files)
                
                QMessageBox.information(self, "成功", f"已在Redis添加Tab: {tab_name}")
                # # 刷新Tab列表
                # self.refresh_tabs()
                # self.tab_combobox.setCurrentText(tab_name)
            except Exception as e:
                traceback.print_exception(e)
                QMessageBox.warning(self, "错误", f"添加Tab '{tab_name}' 失败: {e}")
        elif UserRole.ANNOTATOR in role:
            print("检查权限，无法添加作业")
        elif UserRole.EMEND in role:
            print("检查权限，无法添加作业")
            
        
        